package ua.org.extjsbuilder.parser.runtime.instructions;

import java.io.IOException;
import java.io.Writer;

import ua.org.extjsbuilder.parser.IInstruction;
import ua.org.extjsbuilder.parser.IScope;
import ua.org.extjsbuilder.parser.JSObject;
import ua.org.extjsbuilder.parser.runtime.data.JSConstants;

public class Declare extends AbstractInstruction 
		implements IInstruction {
	private String name;
	private int line;
	private IScope scope;

	public Declare(CharSequence name, int line) {
		this.name = name.toString();
		this.line = line;
	}

	public void compile(Writer out, boolean optimize) throws IOException {
		out.write("var ");
		if(optimize&&scope!=null)
			out.write(scope.getAlly(name));
		else 
			out.write(name);
		out.write(';');
	}

	public JSObject execute(IScope scope, JSObject[] args) {
		this.scope = scope;
		if(scope.isDefinedLocaly(name)){
			warn("Variable "+name+
				" is already defined in this scope",line);
		}
		scope.define(name, JSConstants.NULL);
		return JSConstants.UNDEFINED;
	}

	public String getName() {
		return name;
	}
}
